package com.time.hellotime.views;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.LinearLayout;

import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.time.hellotime.R;
import com.time.hellotime.components.JsListener;
import com.time.hellotime.components.dialog.LoadingDialog;

import org.apache.http.util.EncodingUtils;

/**
 * @author gyw
 * @version 1.0
 * @time: 2015-12-25 下午1:08:25
 * @fun:
 * @fix: 修改加载失败后的错误显示
 */
@SuppressLint("JavascriptInterface")
public class ProgressWebView extends LinearLayout {

    WebView mWebView;

    private Dialog mDialog;

    private Context mContext;

    private String url;

    public ProgressWebView(Context context) {
        this(context, null);
    }

    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView(context);
    }

    public ProgressWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public WebView getmWebView() {
        return mWebView;
    }

    private void initView(Context context) {
        View view = View.inflate(context, R.layout.view_web_progress, this);
        this.mWebView = view.findViewById(R.id.scroll_web_view);
        if (null != context){
            this.mDialog = new LoadingDialog(context);
            this.mDialog.setCancelable(true);
        }

    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void loadUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            url = "";
        }
        initWebView(url);
    }

    public void invokeJs(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        mWebView.loadUrl(url);
    }

    public void postUrl(String url, String para) {
        if (TextUtils.isEmpty(url)) {
            url = "";
        }
        mWebView.postUrl(url, EncodingUtils.getBytes(para, "base64"));
    }

    public void reload() {
        if (null != mWebView) {
            mWebView.reload();
        }
    }

    private void initWebView(String url) {

        WebSettings webSettings = mWebView.getSettings();
        // 设置是否允许执行JS
        webSettings.setJavaScriptEnabled(true);
        // 设置dom存储权限
        webSettings.setDomStorageEnabled(true);
        // 设置缓存模式，优先是用缓存
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置可以访问文件
        webSettings.setAllowFileAccess(true);
        // 设置可以支持缩放
        webSettings.setSupportZoom(true);
        // 设置任意比例缩放
        webSettings.setUseWideViewPort(true);
        // 设置默认缩放方式尺寸是far
        webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        // 设置出现缩放工具
        webSettings.setBuiltInZoomControls(false);
        webSettings.setDefaultFontSize(16);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }

        // 解决图片不显示问题
        webSettings.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(0);
        }

        mWebView.addJavascriptInterface(this, "android");
        // 设置WebViewClient
        mWebView.setWebViewClient(new WebViewClient() {
            // 监听 所有点击的链接，如果拦截到我们需要的，就跳转到相对应的页面。
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 使用自己的WebView组件来响应Url加载事件，而不是使用默认浏览器器加载页面
                view.loadUrl(url);
                // 相应完成返回true
                return true;
                // return super.shouldOverrideUrlLoading(view, url);
            }

            // 页面开始加载
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (null != mDialog){
                    if (!mDialog.isShowing()){
                        mDialog.show();
                    }
                }
                super.onPageStarted(view, url, favicon);
            }

            // 页面加载完成
            @Override
            public void onPageFinished(WebView view, String url) {
                if (null != mDialog){
                    if (mDialog.isShowing()){
                        mDialog.dismiss();
                    }
                }
                super.onPageFinished(view, url);
            }

            // WebView加载的所有资源url
            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//				view.loadData(errorHtml, "text/html; charset=UTF-8", null);
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

        });

        // 设置WebChromeClient
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            // 处理javascript中的alert
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            // 处理javascript中的confirm
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

            @Override
            // 处理javascript中的prompt
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }

            // 设置网页加载的进度条
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            // 设置程序的Title
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        });

        mWebView.loadUrl(url);

    }

    public boolean canBack() {
        return mWebView.canGoBack();
    }

    public void toBack() {
        mWebView.goBack(); // 后退
    }

    private JsListener jsListener;

    public void setJsListener(JsListener jsListener) {
        this.jsListener = jsListener;
    }

    @JavascriptInterface
    public void goBack() {
        if (null != jsListener) {
            jsListener.jsGoBack();
        }
    }

    @JavascriptInterface
    public void goAvatar() {
        if (null != jsListener) {
            jsListener.jsAvatar();
        }
    }

    @JavascriptInterface
    public void goSuggestion() {
        if (null != jsListener) {
            jsListener.jsSuggestion();
        }
    }

    @JavascriptInterface
    public void goCommunicate() {
        if (null != jsListener) {
            jsListener.jsCommunicate();
        }
    }

    @JavascriptInterface
    public void hiddenBottomTab(String tag, String url) {
        if (null != jsListener) {
            jsListener.jsHiddenBottomTab(tag, url);
        }
    }

    @JavascriptInterface
    public void linkShare(String channel, String type, String id) {
        if (null != jsListener) {
            jsListener.jsShare(channel, type, id);
        }
    }

    @JavascriptInterface
    public void goClearCache() {
        if (null != jsListener) {
            jsListener.jsClearCache();
        }
    }

    @JavascriptInterface
    public void goUpdateVersion(String downloadUrl) {
        if (null != jsListener) {
            jsListener.jsUpdateVersion(downloadUrl);
        }
    }

    @JavascriptInterface
    public void goTelephone(String telephone) {
        if (null != jsListener) {
            jsListener.jsTelephone(telephone);
        }
    }

    @JavascriptInterface
    public void goExit() {
        if (null != jsListener) {
            jsListener.jsExit();
        }
    }
}
